package com.example.cardgame.fragments

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.example.cardgame.R
import com.example.cardgame.model.UserInfo
import com.example.cardgame.databinding.FragmentEditBinding
import java.io.ObjectOutputStream

class EditFragment : Fragment() {
    private var _binding: FragmentEditBinding? = null
    private val binding get() = _binding!!
    private val fileName = "user_info.dat"

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentEditBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.buttonSave.setOnClickListener {
            val name = binding.editNameText.text.toString()
            val sid = binding.editSidText.text.toString()
            val phone = binding.editPhoneText.text.toString()
            val email = binding.editEmailText.text.toString()

            val gender = when (binding.radioGender.checkedRadioButtonId) {
                R.id.radioButton1 -> getString(R.string.text_man)
                R.id.radioButton2 -> getString(R.string.text_woman)
                else -> "N/A"
            }

            val hobbies = mutableListOf<String>()
            if (binding.checkBoxTravel.isChecked) hobbies.add(getString(R.string.text_hobby_travel))
            if (binding.checkBoxRead.isChecked) hobbies.add(getString(R.string.text_hobby_read))
            if (binding.checkBoxGame.isChecked) hobbies.add(getString(R.string.text_hobby_game))
            if (binding.checkBoxShopping.isChecked) hobbies.add(getString(R.string.text_hobby_shopping))

            saveUserInfo(UserInfo(name, sid, phone, email, gender, hobbies.joinToString("| "), 0, 0))
            Toast.makeText(context, getString(R.string.text_save_success), Toast.LENGTH_SHORT).show()
            parentFragmentManager.popBackStack()
        }

        binding.buttonCancel.setOnClickListener {
            parentFragmentManager.popBackStack()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun saveUserInfo(userInfo: UserInfo){
        try {
            val fileOutputStream = requireContext().openFileOutput(fileName, 0)
            val objectOutputStream = ObjectOutputStream(fileOutputStream)
            objectOutputStream.writeObject(userInfo)
            objectOutputStream.close()
            fileOutputStream.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}